package com.xianggg.xservers.web;

import com.google.gson.Gson;
import org.apache.tomcat.util.http.fileupload.*;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

@RestController
@RequestMapping("file")
public class FileController {

    @Value("${file.root}")
    private String root;

    @Value("${users}")
    private String users;

    private List<String> getUsers() {
        return Arrays.asList(users.split(","));
    }

    private String getUserPath(String token) {
        if (!getUsers().contains(token)) {
            return null;
        }
        if (token.equals("xiang")) {
            return root;
        } else {
            //新建文件夹
            String parent = root + "/" + token;
            File dir = new File(parent);
            if(!dir.exists()){
                dir.mkdirs();
            }
            return parent;
        }

    }

    @RequestMapping("root")
    public String getFiles(String token, @RequestParam(required = false) String path) {
        String parent = getUserPath(token);
        if (path != null) {
            parent += "/" + path;
        }
        return new Gson().toJson(children(parent));
    }

    @RequestMapping("children")
    public String getChildren(String path) {
        return new Gson().toJson(children(path));
    }

    public List<FileVO> children(String parentPath) {
        File rootDir = new File(parentPath);
        File[] children = rootDir.listFiles();
        List<FileVO> vos = new ArrayList<>();
        if (rootDir.isDirectory() && children != null) {
            for (File child : children) {
                vos.add(new FileVO(child));
            }
        }
        return vos;
    }

    @RequestMapping("mkDir")
    public Boolean mkDir(String token, String path, String name) {
        String parent = getUserPath(token);
        if (parent == null) {
            return false;
        }
        String savePath = getUserPath(token) + "/" + path + "/" + name;
        File dir = new File(savePath);
        return dir.mkdir();
    }

    @RequestMapping("upload")
    public Boolean upload(HttpServletRequest request, HttpServletResponse response, @RequestParam MultipartFile file, String path, String token) throws IOException {
        String parent = getUserPath(token);
        if (parent == null) {
            return false;
        }
        //保存文件到临时目录
        String savePath = parent + "/" + path + "/" + file.getOriginalFilename();
        File saveFile = new File(savePath);
        if (saveFile.exists()) {
            return false;
        }
        file.transferTo(saveFile);
        return true;
    }
    @RequestMapping("download")
    public ResponseEntity<byte[]> downLoad(String path, String token, String name)
            throws Exception {
        String parent = getUserPath(token);
        if (parent == null) {
            return null;
        }
        String filepath = getUserPath(token) + "/" + path + "/" + name;
        File file = new File(filepath);
        if (!file.exists()) {
            return null;
        }
        byte[] body;
        InputStream in = new FileInputStream(file);
        body = new byte[in.available()];
        int read = in.read(body);
        HttpHeaders headers = new HttpHeaders();
        name = new String(name.getBytes("gbk"), "iso8859-1");
        headers.add("Content-Disposition", "attachment;filename=" + name);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        HttpStatus statusCode = HttpStatus.OK;
        ResponseEntity<byte[]> response = new ResponseEntity<>(body, headers, statusCode);
        in.close();
        return response;
    }

    public static void main(String[] args) {
        String root = "d:/PaintToolSI/";
        File rootDir = new File(root);
        File[] children = rootDir.listFiles();
        List<FileVO> vos = new ArrayList<>();
        for (File child : children) {
            vos.add(new FileVO(child));
        }
        System.out.println(new Gson().toJson(vos));

    }
}
